js-events
staging:
master:
Events for push-flow abstractions.
AbstractEvent
class Event1 extends AbstractEvent {}
class Event2 extends AbstractEvent<string> {}
class Event3<T> extends AbstractEvent<T> {}
class Event4<T extends Event = Event> extends AbstractEvent<T> {}
class Event5 extends AbstractEvent<string> {
constructor(options: EventInit & { detail: string }) {
super(Event5.name, options, arguments);
}
}
When redispatching an event, you must call event.clone()
. The same instance cannot be redispatched. When the event is cloned, all constructor parameters are shallow-copied.
Evented
We combine Evented
with AbstractEvent
to gain type-safety and convenience of the wildcard any handler.
class EventCustom extends AbstractEvent {}
interface X extends Evented {}
@Evented()
class X {}
const x = new X();
x.addEventListener(EventCustom.name, (e) => {
console.log(e as EventCustom);
});
x.addEventListener(EventDefault.name, (e) => {
console.log((e as EventDefault).detail);
});
x.addEventListener(EventAll.name, (e) => {
console.log((e as EventAny).detail);
});
You can use this style to handle relevant events to perform side-effects, as well as propagate upwards irrelevant events.
Note that some side-effects you perform may trigger an infinite loop by causing something to emit the specific event type that you are handling. In these cases you should specialise handling of those events with a once: true
option, so that they are only handled once.
x.addEventListener(EventInfinite.name, (e) => {
console.log(e as EventInfinite);
performActionThatMayTriggerEventInfinite();
}, { once: true });
This will terminate the infinite loop on the first time it gets handled.
Therefore it is a good idea to always be as specific with your event types as possible.
Furthermore any unhandled rejections or uncaught exceptions will be redispatched as EventError
. However if there's no listener registered for this, it will be thrown up as an uncaught exception.
Installation
npm install --save @matrixai/events
Development
Run nix-shell
, and once you're inside, you can use:
npm install
npm run build
npm run ts-node
npm run test
npm run lint
npm run lintfix
Docs Generation
npm run docs
See the docs at: https://matrixai.github.io/js-events/
Publishing
Publishing is handled automatically by the staging pipeline.
Prerelease:
npm version prepatch --preid alpha
git push --follow-tags
Release:
npm version patch
git push --follow-tags
Manually:
npm version patch
npm run build
npm publish --access public
git push
git push --tags